﻿using DevExpress.XtraTreeList.Nodes;
using RecruitStudents.Utility;
using RecruitStudents.Utility.Helper;
using RecruitStudents.Utility.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RecruitStudents.Client.Base
{
    public partial class Base_Role_Option : BaseForm
    {
        ///<summary>
        ///所有权限
        ///</summary>
        private List<Privilege> listPrivilege = new List<Privilege>();
        ///<summary>
        ///默认的权限
        ///</summary>
        private List<Privilege> listPrivilegeMoRen = new List<Privilege>();
        string RoleID = string.Empty;
        TB_Sys_Role model = null;
        BLL.ServiceBase service = new BLL.ServiceBase();
        public Base_Role_Option(string strRoleID)
        {
            InitializeComponent();
            RoleID = strRoleID;
            if (RoleID.ToSafeString().Length > 0)
            {
                model = service.GetRoleModel(RoleID);
                if (model != null)
                {
                    model.Attach();
                    txtRoleName.Text = model.RoleName;
                    txtRoleRemark.Text = model.RoleRemark;
                    if (model.IsActive == "1")
                    {
                        chkIsActive.Checked = true;
                    }
                    else
                    {
                        chkIsActive.Checked = false;
                    }
                }
            }
            InitPrivilege();
            InitTreeList();
        }
        private void InitPrivilege()
        {
            using (DataTable dtModel = service.GetModuleTable())
            {
                if (dtModel != null)
                {
                    foreach (DataRow dr in dtModel.Rows)
                    {
                        listPrivilege.Add(new Privilege() { ID = dr["ID"].ToSafeString(), MenuName = dr["MenuName"].ToSafeString(), ModuleID = dr["ModuleID"].ToSafeString(), ParentID = dr["ParentID"].ToSafeString() });
                    }
                }
            }
            if (RoleID.Length > 0)
            {
                using (DataTable dtModel = service.GetRoleAuthModuleTable(RoleID))
                {
                    if (dtModel != null)
                    {
                        foreach (DataRow dr in dtModel.Rows)
                        {
                            listPrivilegeMoRen.Add(new Privilege() { ID = dr["ID"].ToSafeString(), MenuName = dr["MenuName"].ToSafeString(), ModuleID = dr["ModuleID"].ToSafeString(), ParentID = dr["ParentID"].ToSafeString() });
                        }
                    }
                }
            }
        }

        private void InitTreeListChildren(string ParentID)
        {
            List<Privilege> listOne = listPrivilege.Where(p => p.ParentID == ParentID).ToList();
            //加载一级子节点
            foreach (Privilege pri in listOne)
            {
                for (int i = 0; i < treeList1.Nodes.Count; i++)
                {
                    string int_parentId = pri.ParentID;
                    if (int_parentId == (string)(treeList1.Nodes[i].GetValue(this.treeListColumn2)))
                    {
                        this.treeList1.AppendNode(new object[] { pri.MenuName, pri.ModuleID, pri.ParentID, pri.ID, pri }, treeList1.Nodes[i].Id);
                    }
                }
            }
        }

        private void InitTreeList()
        {
            List<Privilege> listRoot = listPrivilege.Where(p => p.ParentID == "0").ToList();
            //加载所有的根节点
            foreach (Privilege pri in listRoot)
            {
                this.treeList1.AppendNode(new object[] { pri.MenuName, pri.ModuleID, pri.ParentID, pri.ID, pri }, -1);
                InitTreeListChildren(pri.ModuleID);
            }
            //将所有的树形节点展开
            //this.treeList1.ExpandAll();
            foreach (TreeListNode t in this.treeList1.Nodes)
            {
                if (t != null)
                {
                    SetNodeChecked(t, listPrivilegeMoRen);
                }
            }
        }
        private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            if (e.Node == null)
            { return; }
            //选中父节点，其下的所有子节点都被选中
            if (e.Node.CheckState == CheckState.Checked)
            {
                if (e.Node.HasChildren)
                {
                    CheckNode(e.Node);
                }
                if (e.Node.ParentNode != null)
                {
                    if (e.Node.ParentNode.CheckState != CheckState.Checked)
                    {

                        e.Node.ParentNode.CheckState = CheckState.Checked;
                        SetParentNodeChecked(e.Node.ParentNode);
                    }
                }
            }
            if (e.Node.CheckState == CheckState.Unchecked)
            {
                if (e.Node.ParentNode != null)
                {
                    //判断一下该父节点下的子节点是否都已经处于非选中状态
                    if (IsAllChildrenUnChecked(e.Node.ParentNode))
                    {
                        e.Node.ParentNode.CheckState = CheckState.Unchecked;
                    }
                }
            }
            //取消父节点，其下的所有子节点都是处于非选中状态
            if (e.Node.CheckState == CheckState.Unchecked)
            {
                if (e.Node.HasChildren)
                {
                    ClearNode(e.Node);
                }
            }
            if (e.Node.CheckState == CheckState.Checked)
            {
                //m_role.PrivilegesList.Add(((Privilege)e.Node.GetValue(this.pri)));
            }
        }

        private bool IsAllChildrenUnChecked(TreeListNode tnode)
        {
            foreach (TreeListNode cNode in tnode.Nodes)
            {
                if (cNode.CheckState != CheckState.Unchecked)
                {
                    return false;
                }
            }
            return true;
        }
        private void ClearNode(TreeListNode node)
        {
            foreach (TreeListNode cNode in node.Nodes)
            {
                if (cNode != null)
                {
                    cNode.CheckState = CheckState.Unchecked;
                }
                if (cNode.HasChildren)
                {
                    ClearNode(cNode);
                }
            }
        }
        //如果点击了父节点，则相应的子节点全部被选中
        private void CheckNode(DevExpress.XtraTreeList.Nodes.TreeListNode node)
        {
            foreach (TreeListNode cNode in node.Nodes)
            {
                if (cNode != null)
                {
                    if (cNode.CheckState == CheckState.Unchecked)
                    {
                        cNode.CheckState = CheckState.Checked;
                        //m_role.PrivilegesList.Add(((Privilege)cNode.GetValue(this.pri)));
                    }
                }
                if (cNode.HasChildren)
                {
                    CheckNode(cNode);
                }
            }
        }
        private void SetNodeChecked(TreeListNode node, List<Privilege> listP)
        {
            if (listP != null)
            {
                if (node != null)
                {
                    for (int i = 0; i < listP.Count; i++)
                    {
                        if (listP[i] != null && (string)node.GetValue(this.treeListColumn4) == listP[i].ID)
                        {
                            node.CheckState = CheckState.Checked;
                            SetParentNodeChecked(node);
                        }
                    }
                    foreach (TreeListNode tnode in node.Nodes)
                    {
                        SetNodeChecked(tnode, listP);
                    }
                }
                if (node == null)
                    return;
            }
        }
        //如果选中子节点，则相应的父节点都被选中
        private void SetParentNodeChecked(TreeListNode node)
        {
            try
            {
                if (node.ParentNode != null)
                {
                    if (node.ParentNode.CheckState == CheckState.Unchecked)
                    {
                        node.ParentNode.CheckState = CheckState.Checked;
                        //m_role.PrivilegesList.Add(((Privilege)node.GetValue(this.pri)));
                    }
                    SetParentNodeChecked(node.ParentNode);
                }
                if (node.ParentNode == null)
                    return;
            }
            catch (Exception)
            {
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtRoleName.Text.ToSafeString().Length == 0)
            {
                DevHelper.ShowInfoMessageBox("请先输入角色名称!");
                this.txtRoleName.Focus();
                return;
            }
            if (model == null)
            {
                model = new TB_Sys_Role();
                model.CreateDate = DateTime.Now;
            }
            model.IsActive = chkIsActive.Checked ? "1" : "0";
            model.RoleRemark = txtRoleRemark.Text;
            model.RoleName = txtRoleName.Text;
            List<TB_Sys_RoleAuth> listRoleAuth = new List<TB_Sys_RoleAuth>();
            foreach (TreeListNode tnode in this.treeList1.Nodes)
            {
                GetAllPrivelege(tnode, listRoleAuth, model.RoleID);
            }
            if (listRoleAuth.Count == 0)
            {
                DevHelper.ShowInfoMessageBox("该角色还没有分配任何权限模块!");
                return;
            }
            if (service.SaveRole(model, listRoleAuth))
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
        //递归树，找出所有的选中权限
        public void GetAllPrivelege(TreeListNode tnode, List<TB_Sys_RoleAuth> listRoleAuth, string strRoleID)
        {
            if (tnode != null)
            {
                if (tnode.CheckState == CheckState.Checked)
                {
                    listRoleAuth.Add(new TB_Sys_RoleAuth() { RoleID = strRoleID, ModuleID = (string)tnode.GetValue(this.treeListColumn2) });
                }
                foreach (TreeListNode node in tnode.Nodes)
                {
                    GetAllPrivelege(node, listRoleAuth, strRoleID);
                }
            }
            else
            {
                return;
            }
        }

    }



    class Privilege
    {
        ///<summary>
        ///权限ID
        ///</summary>
        public string ID { get; set; }
        ///<summary>
        ///权限ID
        ///</summary>
        public string ModuleID { get; set; }
        ///<summary>
        ///权限名称
        ///</summary>
        public string MenuName { get; set; }
        ///<summary>
        ///父节点
        ///</summary>
        public string ParentID { get; set; }
    }
}
